using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 世界观设定工具测试程序
    /// </summary>
    public class TestWorldSettingTools
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("=== 世界观设定工具测试程序 ===");
            Console.WriteLine();

            try
            {
                // 获取服务
                var serviceProvider = App.ServiceProvider;
                if (serviceProvider == null)
                {
                    Console.WriteLine("错误：ServiceProvider 未初始化");
                    return;
                }

                var projectToolsService = serviceProvider.GetRequiredService<IProjectToolsService>();
                var logger = serviceProvider.GetRequiredService<ILogger<TestWorldSettingTools>>();

                Console.WriteLine("1. 测试世界观设定分析器...");
                await TestWorldSettingAnalyzer(projectToolsService);

                Console.WriteLine("\n2. 测试世界观设定读取器...");
                await TestWorldSettingReader(projectToolsService);

                Console.WriteLine("\n3. 测试章节细纲增强器...");
                await TestChapterOutlineEnhancer(projectToolsService);

                Console.WriteLine("\n=== 测试完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"测试过程中发生错误: {ex.Message}");
                Console.WriteLine($"详细错误: {ex}");
            }

            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }

        /// <summary>
        /// 测试世界观设定分析器
        /// </summary>
        private static async Task TestWorldSettingAnalyzer(IProjectToolsService projectToolsService)
        {
            try
            {
                var parameters = new Dictionary<string, object>
                {
                    ["projectPath"] = @"D:\AI_project\文档管理及创作系统\DocumentCreationSystem\示例项目",
                    ["analysisType"] = "全面分析",
                    ["includeRecommendations"] = true
                };

                Console.WriteLine("执行世界观设定分析器...");
                var result = await projectToolsService.ExecuteToolAsync("world-setting-analyzer", parameters);

                if (result.IsSuccess)
                {
                    Console.WriteLine("✓ 分析成功");
                    Console.WriteLine($"消息: {result.Message}");
                    
                    if (result.Data.ContainsKey("foundFiles"))
                    {
                        var foundFiles = result.Data["foundFiles"] as List<string>;
                        Console.WriteLine($"找到的文件数量: {foundFiles?.Count ?? 0}");
                        if (foundFiles != null && foundFiles.Count > 0)
                        {
                            Console.WriteLine("找到的文件:");
                            foreach (var file in foundFiles)
                            {
                                Console.WriteLine($"  - {file}");
                            }
                        }
                    }

                    if (result.Data.ContainsKey("completeness"))
                    {
                        var completeness = result.Data["completeness"];
                        Console.WriteLine($"完整度: {completeness}%");
                    }

                    if (result.Data.ContainsKey("recommendations"))
                    {
                        var recommendations = result.Data["recommendations"] as List<string>;
                        if (recommendations != null && recommendations.Count > 0)
                        {
                            Console.WriteLine("建议:");
                            foreach (var recommendation in recommendations)
                            {
                                Console.WriteLine($"  - {recommendation}");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("✗ 分析失败");
                    Console.WriteLine($"错误: {result.ErrorDetails}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ 测试世界观设定分析器时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试世界观设定读取器
        /// </summary>
        private static async Task TestWorldSettingReader(IProjectToolsService projectToolsService)
        {
            try
            {
                var parameters = new Dictionary<string, object>
                {
                    ["projectPath"] = @"D:\AI_project\文档管理及创作系统\DocumentCreationSystem\示例项目",
                    ["settingFiles"] = "世界观设定管理.md",
                    ["outputFormat"] = "summary"
                };

                Console.WriteLine("执行世界观设定读取器...");
                var result = await projectToolsService.ExecuteToolAsync("world-setting-reader", parameters);

                if (result.IsSuccess)
                {
                    Console.WriteLine("✓ 读取成功");
                    Console.WriteLine($"消息: {result.Message}");
                    
                    if (result.Data.ContainsKey("contents"))
                    {
                        var contents = result.Data["contents"] as Dictionary<string, object>;
                        if (contents != null)
                        {
                            Console.WriteLine("读取的内容:");
                            foreach (var content in contents)
                            {
                                Console.WriteLine($"文件: {content.Key}");
                                var contentText = content.Value?.ToString();
                                if (!string.IsNullOrEmpty(contentText))
                                {
                                    // 只显示前200个字符
                                    var preview = contentText.Length > 200 
                                        ? contentText.Substring(0, 200) + "..." 
                                        : contentText;
                                    Console.WriteLine($"内容预览: {preview}");
                                }
                                Console.WriteLine();
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("✗ 读取失败");
                    Console.WriteLine($"错误: {result.ErrorDetails}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ 测试世界观设定读取器时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试章节细纲增强器
        /// </summary>
        private static async Task TestChapterOutlineEnhancer(IProjectToolsService projectToolsService)
        {
            try
            {
                var sampleOutline = @"## 第1章：觉醒之始

### 场景设定
- 时间：现代都市，深夜时分
- 地点：市立图书馆古籍阅览室
- 环境：昏暗安静，月光透过窗户洒在古老的书架上

### 人物安排
- 主要人物：林轩（大学生，22岁，对古籍有浓厚兴趣）
- 次要人物：图书馆管理员老张

### 主线发展
- 核心事件：林轩意外触碰古籍，激活其中的修真传承
- 爽点设计：古籍突然发光，神秘力量涌入体内
- 冲突点：力量觉醒带来的身体剧痛和意识冲击

### 预期结果
- 情节推进：开启修真之路，为后续修炼打下基础
- 角色成长：从普通大学生转变为修真者";

                var parameters = new Dictionary<string, object>
                {
                    ["chapterOutline"] = sampleOutline,
                    ["projectPath"] = @"D:\AI_project\文档管理及创作系统\DocumentCreationSystem\示例项目",
                    ["chapterNumber"] = 1,
                    ["enhancementLevel"] = "标准"
                };

                Console.WriteLine("执行章节细纲增强器...");
                var result = await projectToolsService.ExecuteToolAsync("chapter-outline-enhancer", parameters);

                if (result.IsSuccess)
                {
                    Console.WriteLine("✓ 增强成功");
                    Console.WriteLine($"消息: {result.Message}");
                    
                    if (result.Data.ContainsKey("enhancedOutline"))
                    {
                        var enhancedOutline = result.Data["enhancedOutline"]?.ToString();
                        if (!string.IsNullOrEmpty(enhancedOutline))
                        {
                            Console.WriteLine("增强后的细纲:");
                            // 只显示前500个字符
                            var preview = enhancedOutline.Length > 500 
                                ? enhancedOutline.Substring(0, 500) + "..." 
                                : enhancedOutline;
                            Console.WriteLine(preview);
                        }
                    }

                    if (result.Data.ContainsKey("usedWorldSettings"))
                    {
                        var usedSettings = result.Data["usedWorldSettings"] as List<string>;
                        if (usedSettings != null && usedSettings.Count > 0)
                        {
                            Console.WriteLine("\n使用的世界观设定:");
                            foreach (var setting in usedSettings)
                            {
                                Console.WriteLine($"  - {setting}");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("✗ 增强失败");
                    Console.WriteLine($"错误: {result.ErrorDetails}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ 测试章节细纲增强器时发生异常: {ex.Message}");
            }
        }
    }
}
